package com.free.chat.web;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.free.chat.entity.ApiResult;
import com.free.chat.entity.dto.TopicCollectDTO;
import com.free.chat.entity.dto.TopicDTO;
import com.free.chat.entity.model.Topic;
import com.free.chat.entity.model.TopicCollectRelation;
import com.free.chat.exception.ApiException;
import com.free.chat.service.TopicService;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.*;

import java.util.Date;
import java.util.List;

@Controller
@Mapping("topic")
@Slf4j
public class TopicController {

    @Inject
    private TopicService topicService;

    @Get
    @Mapping("list")
    public ApiResult list(Topic topic) {
        LambdaQueryWrapper<Topic> queryWrapper = new LambdaQueryWrapper<>(topic);
        List<Topic> topics = topicService.list(queryWrapper);
        return ApiResult.success(topics);
    }

    @Post
    @Mapping("add")
    public ApiResult add(Topic topic) {
        try {
            topic.setId(IdUtil.getSnowflakeNextId());
            // topic.setUserId(StpUtil.getLoginIdAsLong());
            topic.setReleaseTime(new Date());
            topic.setCreateTime(new Date());
            topic.setDeleted(Boolean.FALSE);
            topicService.save(topic);
        } catch (Exception e) {
            log.error("【topic插入失败】", e);
            throw new ApiException("帖子创建异常");

        }
        return ApiResult.success();
    }

    @Get
    @Mapping("del")
    public ApiResult del(Long id) {
        if (topicService.removeById(id)) {
            return ApiResult.successMsg("删除成功");
        }
        return ApiResult.error("删除失败");
    }

    /**
     * @Author: 朝花不迟暮
     * @Description: 根据用户获取帖子
     * @Date: 2022/11/27
     * @Param: topicDTO 查询条件带分页
     */
    @Get
    @Mapping("getTopicListByUser")
    public ApiResult getTopicListByUser(TopicDTO topicDTO) {
        return topicService.getTopicListByUser(topicDTO);
    }

    /**
     * @Author: 朝花不迟暮
     * @Description: 收藏帖子
     * @Date: 2022/11/28
     */
    @Get
    @Mapping("collectTopic")
    public ApiResult collectTopic(TopicCollectDTO topicCollectDTO) {
        return topicService.collectTopic(topicCollectDTO);
    }
}
